package com.mjk.common.tools.gson.adapter.impl;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import com.mjk.common.util.ObjectUtils;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateAdapterImpl extends TypeAdapter<Date> {


	@Override
	public void write(JsonWriter out, Date value) throws IOException {
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateFormatAsString = "";
		if(ObjectUtils.isNotEmpty(value)){
			 dateFormatAsString = format.format(new Date(value.getTime()));				
		}
		out.value(dateFormatAsString);
	}

	@Override
	public Date read(JsonReader in) throws IOException {
		if (in.peek() == JsonToken.NULL) {
			return null;
		}
		String str = in.nextString();
		try {
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = format.parse(str);
			return new Date(date.getTime());
		} catch (Exception e) {
			Date date;
			try {
				DateFormat format2 = new SimpleDateFormat("HH:mm:ss");
				date = format2.parse(str);
				return new Date(date.getTime());
			} catch (Exception e1) {
				try {
				DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
				date = format2.parse(str);
				return new Date(date.getTime());
				}catch (ParseException e2) {
					return null;
				}
			}
		}
	}

}
